<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <el-tabs>
          <!-- 放置页签 -->
          <el-tab-pane label="角色管理">
            <!-- 新增角色按钮 -->
            <el-row style="height:60px">
              <el-button
                icon="el-icon-plus"
                size="small"
                type="primary"
                @click="addrows"
              >新增角色</el-button>
            </el-row>
            <!-- 表格 -->
            <el-table border="" :data="rolelist">
              <el-table-column label="序号" width="120">
                <template #default="{$index}">
                  {{ (page.page-1 )*page.pagesize+$index+1 }}
                </template>
              </el-table-column>
              <el-table-column label="角色名称" width="240" prop="name" />
              <el-table-column label="描述" prop="description" />
              <el-table-column label="操作">
                <template #default="{row}">
                  <el-button size="small" type="success" :disabled="!disable('fenpei')" @click="permissionSetting(row.id)">分配权限</el-button>
                  <el-button size="small" type="primary" :disabled="!disable('edit')" @click="getstaff(row.id)">编辑</el-button>
                  <el-button size="small" type="danger" @click="defrows(row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <!-- 分页组件 -->
            <el-row type="flex" justify="center" align="middle" style="height: 60px">
              <!-- 分页组件 -->
              <el-pagination
                :current-page="page.page"
                :page-size="page.pagesize"
                layout="prev, pager, next"
                :total="total"
                @current-change="changePage"
              />
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="公司信息">
            <el-alert
              title="对公司名称、公司地址、营业执照、公司地区的更新，将使得公司资料被重新审核，请谨慎修改"
              type="info"
              show-icon
              :closable="false"
            />
            <el-form label-width="120px" style="margin-top:50px">
              <el-form-item label="公司名称">
                <el-input v-model="formData.name" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="公司地址">
                <el-input v-model="formData.companyAddress" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input v-model="formData.mailbox" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="备注">
                <el-input v-model="formData.remarks" type="textarea" :rows="3" disabled style="width:400px" />
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-card>
      <el-dialog :title="rows.id?'编辑弹层':'创建角色'" :visible="dialogVisible" @close="btnCancel">
        <el-form ref="roleForm" :model="rows" :rules="rules" label-width="120px">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="rows.name" />
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input v-model="rows.description" />
          </el-form-item>
        </el-form>
        <!-- 底部 -->
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button size="small" @click="btnCancel">取消</el-button>
            <el-button size="small" type="primary" @click="btnOK">确定</el-button>
          </el-col>
        </el-row>
      </el-dialog>
      <el-dialog title="角色权限分配" :visible="showPermission" @close="closePermission">
        <el-tree
          ref="mytree"
          :props="{label:'name'}"
          :data="PermissionList"
          :show-checkbox="true"
          :check-strictly="true"
          node-key="id"
        />
        <el-button size="small" @click="closePermission">取消</el-button>
        <el-button size="small" type="primary" @click="permissionBtn">确定</el-button>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { company, roleList, delRows, getstaff, editRole, addRows, setRoot } from '@/api/setting'
import { getPermission } from '@/api/permission'
import { mapGetters } from 'vuex'
import recursion from '@/utils/recursion'
export default {
  data() {
    const chekName = async(rule, value, callback) => {
      let isRoot = false
      const { rows } = await roleList({ page: 1, pagesize: this.total })
      if (this.rows.id) {
        isRoot = rows.some(item => item.name === value && item.id !== this.rows.id)
      } else {
        isRoot = rows.some(item => item.name === value)
      }
      if (!isRoot) {
        callback()
      } else {
        callback(new Error('角色名称不能重复'))
      }
    }
    return {
      dialogVisible: false,
      showPermission: false,
      PermissionList: [],
      userId: '',
      checkedPermission: [],
      formData: [],
      rolelist: [],
      rows: {
        name: '',
        description: ''
      },
      page: {
        page: 1,
        pagesize: 2
      },
      total: 1,
      rules: {
        name: [{ trigger: 'blur', message: '名称不能为空', required: true }, {
          trigger: 'blur', required: true, validator: chekName }],
        description: [{ trigger: 'blur', message: '角色描述不能为空', required: true }]
      }
    }
  },
  computed: {
    ...mapGetters(['UserInfo'])
  },
  created() {
    this.getcompany()
    this.getrows()
  },
  methods: {
    async permissionBtn() {
      const res = this.$refs.mytree.getCheckedKeys()
      console.log(res)
      await setRoot({ permIds: res, id: this.userId })
      this.$message.success('权限分配成功')
      this.showPermission = false
    },
    async permissionSetting(id) {
      this.userId = id
      this.checkedPermission = []
      this.PermissionList = recursion((await getPermission()), '0')
      const { permIds } = await getstaff(id)
      this.checkedPermission = permIds
      this.showPermission = true
      this.$nextTick(() => {
        this.$refs.mytree.setCheckedKeys(this.checkedPermission)
      })
    },
    async getcompany() {
      this.formData = await company(this.UserInfo.companyId)
    },
    async getrows() {
      const { rows, total } = (await roleList(this.page))
      this.rolelist = rows
      this.total = total
    },
    changePage(page) {
      this.page.page = page
      this.getrows()
    },
    async defrows(delId) {
      try {
        await this.$confirm('确定要删除吗？')
        await delRows(delId)
      } catch (error) {
        console.log(error)
      }
      if (this.rows.length === 1 && this.page.page > 1) {
        this.page.page--
        this.getrows()
      } else {
        this.getrows()
      }
    },
    async getstaff(id) {
      this.rows = await getstaff(id)
      this.dialogVisible = true
    },
    btnCancel() {
      this.dialogVisible = false
      this.$refs.roleForm.resetFields()
      this.rows = {
        name: '',
        description: ''
      }
    },
    async btnOK() {
      this.$refs.roleForm.validate()
      if (this.rows.id) {
        await editRole(this.rows.id, this.rows)
        this.getrows()
      } else {
        await addRows(this.rows)
      }
      this.btnCancel()
    },
    async addrows() {
      this.dialogVisible = true
    },
    closePermission() {
      this.checkedPermission = []
      this.showPermission = false
    }
  }
}
</script>

<style>

</style>
